package edu.njust.cma.controller;

import edu.njust.cma.DTO.Excel04;
import edu.njust.cma.DTO.Excel05;
import edu.njust.cma.DTO.ImportExcel;
import edu.njust.cma.pojo.Equipment;
import edu.njust.cma.pojo.Result;
import edu.njust.cma.pojo.Standard;
import edu.njust.cma.service.EquipService;
import edu.njust.cma.service.StandardService;
import edu.njust.cma.util.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@RestController
public class FileController {
    /**
     * 1. 生成Excel文件
     * 2. 上传pdf证明材料
     * 3. 下载pdf证明材料
     */
    @Autowired
    AliOSSUtils aliOSSUtils;

    //1. 生成Excel文件
    @Autowired
    private EquipService equipService;
    @Autowired
    private StandardService standardService;

    //生成Excel03
        @GetMapping("/export/excel03")
        public ResponseEntity<InputStreamResource> exportDataToExcel03() throws IOException {
            List<Equipment> dataList = equipService.equipList();
            XSSFWorkbook workbook = ExcelUtil03.createExcelFile(dataList);

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            workbook.write(byteArrayOutputStream);
            workbook.close();

            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());

            // 设置文件名，使用当前日期时间作为文件名
            String originalFilename = "03 仪器设备信息表.xlsx";
            String encodedFilename = URLEncoder.encode(originalFilename, StandardCharsets.UTF_8.toString());
            
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFilename);

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(new InputStreamResource(byteArrayInputStream));
        }

    //生成Excel04
    @GetMapping("/export/excel04/{projectId}")
    public ResponseEntity<InputStreamResource> exportDataToExcel04(@PathVariable int projectId) throws IOException {
        List<Excel04> dataList = equipService.equipListExcel04(projectId);
        XSSFWorkbook workbook = ExcelUtil04.createExcelFile(dataList);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        workbook.close();

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());


        String originalFilename = "04 检验检测能力申请表.xlsx";
        String encodedFilename = URLEncoder.encode(originalFilename, StandardCharsets.UTF_8.toString());

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFilename);

        return ResponseEntity.ok()
                .headers(headers)
                .body(new InputStreamResource(byteArrayInputStream));
    }

    //生成Excel05
    @GetMapping("/export/excel05/{projectId}")
    public ResponseEntity<InputStreamResource> exportDataToExcel05(@PathVariable int projectId) throws IOException {
        List<Excel05> dataList = equipService.equipListExcel05(projectId);
        XSSFWorkbook workbook = ExcelUtil05.createExcelFile(dataList);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        workbook.close();

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());


        String originalFilename = "05 仪器设备（标准物质）配置表.xlsx";
        String encodedFilename = URLEncoder.encode(originalFilename, StandardCharsets.UTF_8.toString());

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFilename);

        return ResponseEntity.ok()
                .headers(headers)
                .body(new InputStreamResource(byteArrayInputStream));
    }

    //2. 上传pdf证明材料
    @PostMapping("/upload")
    public Result upload(@RequestBody MultipartFile file) throws IOException {
        //调用阿里云OSS工具类上传文件
        String url = aliOSSUtils.upload(file);
        //返回成功
        return Result.success(url);
    }

    //3. 导入Excel文件添加标准库（standards）信息
    @PostMapping("/import/excel")
    public Result importData(@RequestBody MultipartFile file) throws Exception {
        //调用工具类解析Excel文件
        List<ImportExcel> dataList = ExcelImportUtils.readExcel(file);
        dataList.remove(0);
        if(dataList.size() == 0){
            return Result.error("导入失败");
        }
        //将解析出来的数据封装成Standard对象
        List<Standard> standardList = new ArrayList<>();

        for (ImportExcel importExcel : dataList) {
            Standard standard = new Standard();
            standard.setMajorCategoryName(importExcel.getMajorCategoryName());
            standard.setMinorCategoryName(importExcel.getMinorCategoryName());
            standard.setNumber(importExcel.getStandardNumber());
            standard.setName(importExcel.getStandardName());
            // 设置其他属性
            standardList.add(standard);
        }

        /**
         * 保证数据不重复,利用id去重
         */

        int id= 0;
        //调用service层方法将数据存入数据库
        for(int i= 0; i < standardList.size(); i++){
           Standard standard = standardList.get(i);
           if(i == 0) {
                id = standardService.addStandard(standard);
              }
              else{
                Standard standardFront = standardList.get(i-1);
                if(!standardFront.getNumber().equals(standard.getNumber())){
                    id = standardService.addStandard(standard);
                }
           }
              standardService.addStandardMethod(id, dataList.get(i).getMethodName());
         }
        //返回成功
        return Result.success("导入数据成功");
    }

}
